package com.yunlongn.common.json.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yunlongn.common.json.jackson.factory.AbstractJsonDeserializer;
import com.yunlongn.common.json.jackson.factory.AbstractJsonSerializer;
import com.yunlongn.common.json.util.DateFormatUtils;
import com.yunlongn.common.json.util.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateTime序列化
 * @author Yun
 * @since 20210902
 */
public class LocalDateTimeSerializer extends AbstractJsonSerializer<LocalDateTime> {

    private int zone;
    private DateTimeFormatter formatter;

    public LocalDateTimeSerializer() {
        this.zone = 8;
        this.formatter = null;
    }

    public LocalDateTimeSerializer(int zone, String datePattern) {
        this.zone = zone;
        if (datePattern == null) {
            this.formatter = null;
            return;
        }
        this.formatter = DateTimeFormatter.ofPattern(datePattern);
    }

    @Override
    public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (formatter == null) {
            jsonGenerator.writeNumber(localDateTime.toInstant(ZoneOffset.ofHours(zone)).toEpochMilli());
        } else {
            jsonGenerator.writeString(localDateTime.format(formatter));
        }
    }

}
